package com.yh.servlet.admin;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/code.let")
public class CodeServlet extends HttpServlet {

	/**
	 * 手写验证码
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 随机数
		Random r = new Random();

		// 设置验证码图片的宽高
		int width = 102;
		int height = 48;

		// 加载图片
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 得到画笔
		Graphics g = img.getGraphics();

		// 填充白色背景
		g.setColor(new Color(255, 255, 255));// 设置颜色
		g.fillRect(0, 0, width, height);// 填充

		// 画干扰线(多条)
		for (int i = 0; i < height / 2; i++) {
			g.setColor(new Color(150 + r.nextInt(100), 150 + r.nextInt(100), 150 + r.nextInt(100)));// 随机颜色；150-250
			g.drawLine(0, r.nextInt(height), width, r.nextInt(height));
		}

		// 绘制文字
		String code = "" + r.nextInt(10) + r.nextInt(10) + r.nextInt(10) + r.nextInt(10);// 随机要绘制的文字
		int fontSize = 32;
		g.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
		int w = width / code.length();
		for (int i = 0; i < code.length(); i++) {
			g.setColor(new Color(50 + r.nextInt(150), 50 + r.nextInt(150), 50 + r.nextInt(150)));// 随机颜色；50-200
			g.drawString(code.substring(i, i + 1), i * w, height - r.nextInt(height - fontSize));
		}

//		System.out.println(code);
		req.getSession().setAttribute("code", code);
		
		resp.reset();//response.reset() 清除首部的空白行
		resp.setContentType("image/jpeg");
		ImageIO.write(img, "jpg", resp.getOutputStream());
		resp.flushBuffer();
	}

}
